package com.lujianfei.tiananyungu

import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.defaultMinSize
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Clear
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.snapshots.SnapshotStateList
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.lujianfei.tiananyungu.shopmanager.Restaurant
import com.lujianfei.tiananyungu.shopmanager.ShopDataManager
import com.lujianfei.tiananyungu.ui.theme.TiananyunguTheme
import com.lujianfei.tiananyungu.utils.SortUtils
import kotlinx.coroutines.flow.flow


/**
 * Author: lujianfei
 * Date: 2024/12/26 10:12
 * Description: 搜索界面
 */

class SearchActivity  : ComponentActivity() {

    companion object {
        fun start(context:Context) {
            context.startActivity(Intent(context, SearchActivity::class.java))
        }
    }

    override fun onBackPressed() {
        super.onBackPressed()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            TiananyunguTheme {
                // A surface container using the 'background' color from the theme
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = MaterialTheme.colorScheme.background
                ) {
                    Main()
                }
            }
        }
    }
}

@OptIn(ExperimentalFoundationApi::class)
@Composable
private fun Main(modifier: Modifier = Modifier) {
    val list = remember {
        mutableStateListOf<HeadItem>()
    }
    val searchText = remember {
        mutableStateOf("")
    }
    val focusRequester = remember { FocusRequester() }
    Column(modifier = modifier.fillMaxSize()) {
        Box(modifier = Modifier.fillMaxWidth()) {
            TextField(
                value = searchText.value,
                onValueChange = {
                    searchText.value = it
                },
                placeholder = { Text("搜索关键字") },
                modifier = Modifier.fillMaxWidth().focusRequester(focusRequester)
            )
            if (searchText.value.isNotEmpty()) {
                Icon(Icons.Default.Clear, contentDescription = "Clear text", modifier = Modifier.align(Alignment.CenterEnd).padding(end = 15.dp).clickable {
                    searchText.value = ""
                })
            }
        }

        LazyColumn(contentPadding = PaddingValues(bottom = 30.dp)) {
            list.forEach { headItem->
                stickyHeader {
                    Header(headItem)
                }
                items(headItem.list) {
                    Item(it)
                }
            }
        }
    }

    LaunchedEffect(Unit) {
        focusRequester.requestFocus()
    }

    LoadData(list = list, searchText = searchText.value)
}

@Composable
private fun Item(it: Restaurant) {
    Box(
        Modifier
            .fillMaxWidth()
            .defaultMinSize(minHeight = 20.dp)) {
        Row(modifier = Modifier
            .align(Alignment.CenterStart)
            .padding(horizontal = 15.dp)
            .fillMaxWidth()
        ) {
            Text(text = it.name, fontSize = 20.sp, modifier = Modifier.weight(1f))
            Text(text = "${it.block}${it.floor}" , fontSize = 20.sp, textAlign = TextAlign.End)
        }
    }
}


@Composable
private fun LoadData(
    list: SnapshotStateList<HeadItem>,
    searchText: String = ""
) {
    list.clear()
    LaunchedEffect(key1 = searchText) {
        flow {
            emit(ShopDataManager.instance.load())
        }.collect { restaurantList ->
            val setType = mutableSetOf<String>()
            val setSubType = mutableMapOf<String,MutableSet<String>>()

            // 用于构建树结构
            val mapBuildingRestaurant = mutableMapOf<String, MutableList<Restaurant>>()
            restaurantList.forEach {
                setType.add(it.sub_type)
                it.sub_sub_type?.let {sub_sub_type->
                    if (setSubType.containsKey(it.sub_type)) {
                        setSubType[it.sub_type]?.add(sub_sub_type)
                    } else {
                        setSubType[it.sub_type] = mutableSetOf(sub_sub_type)
                    }
                }
                val buildingKey = "${it.area}${it.building}"
                if (mapBuildingRestaurant.containsKey(buildingKey)) {
                    mapBuildingRestaurant[buildingKey]?.add(it)
                } else {
                    mapBuildingRestaurant[buildingKey] = arrayListOf(it)
                }
            }
            // 对 key （n栋）进行排序
            for (mapitem in mapBuildingRestaurant) {
                val sublist = mutableStateListOf<Restaurant>()
                mapitem.value.forEach {
                    if (searchText.isNotBlank()) {
                        if (it.name.lowercase().contains(searchText.lowercase().trim())) {
                            sublist.add(it)
                        }
                    } else {
                        sublist.add(it)
                    }
                }
                sublist.sortWith(SortUtils.SubItemSort())
                if (sublist.isNotEmpty()) {
                    list.add(HeadItem(title = mapitem.key, list = sublist))
                }
            }
            list.sortWith(SortUtils.HeadItemSort())
        }
    }
}